// components/chat/chat.ts
// logOffTip
// blackNameTip
import tran from "../../utils/language";
Component({
    pageLifetimes: {
        show() {
            const innerAudioContext = wx.createInnerAudioContext({
                useWebAudioImplement: true,
            });
            this.setData({
                innerAudioContext,
            });
        },
    },
    /**
     * 组件的属性列表
     */
    properties: {
        blackNameFlag: {
            type: Boolean,
            value: false,
            observer(newVal, old, path) {
                // 在这里处理值变化逻辑
                if (newVal) {
                }
            },
        },
        friendStatus: {
            type: Object,
            value: {
                friend: true,
                blockedByTarget: false,
                logout: false,
            },
            observer(newVal, old, path) {
                this.setData({ friendStatus: newVal });
            },
        },
        isInput: {
            type: Boolean,
            value: false,
            observer(newVal, old, path) {
                // 在这里处理值变化逻辑
                this.setData({
                    isInput: newVal,
                });
            },
        },
        userId: {
            type: String,
            value: "",
            observer(newVal, old, path) {
                this.setData({
                    userId: newVal,
                });
            },
        },
        messages: {
            type: Array,
            value: [],
            observer(newVal, old, path) {
                // 在这里处理值变化逻辑
                if (newVal && newVal.length) {
                    newVal.forEach((item) => {
                        if (item.type == "txt") {
                            if (
                                item.msg.indexOf("http://") != -1 ||
                                item.msg.indexOf("https://") != -1 ||
                                item.msg.indexOf("Http://") != -1 ||
                                item.msg.indexOf("Https://") != -1
                            ) {
                                // 正则表达式匹配超链接
                                const urlPattern = /(https?:\/\/[^\s]+)/g;
                                const text = item.msg;
                                // 使用正则表达式匹配所有超链接
                                const urls = text.match(urlPattern);
                                // 构建富文本数据
                                let richTextNodes = [];
                                let lastIndex = 0;
                                urls.forEach((url) => {
                                    const index = text.indexOf(url, lastIndex);
                                    if (index > lastIndex) {
                                        // 添加普通文本节点
                                        richTextNodes.push({
                                            type: "text",
                                            text: text.substring(
                                                lastIndex,
                                                index
                                            ),
                                            style: "color: black;",
                                        });
                                    }
                                    // 添加超链接节点
                                    richTextNodes.push(
                                        // {
                                        //   type: 'text',
                                        //   text: url,
                                        //   style: 'color: #4e78fe; text-decoration: underline;',
                                        //   event: 'tap',
                                        //   attr: {
                                        //     url: url,
                                        //     // style: 'line-height: 60px; color: red;'
                                        //     // class: 'text_class',
                                        //     // style: 'line-height: 60px; color: red;'
                                        //   }
                                        // }
                                        {
                                            name: "span",
                                            event: "tap",
                                            text: url,
                                            url: url,
                                            attrs: {
                                                url: url,
                                                class: "div_class",
                                                style: "color: #4e78fe; text-decoration: underline;",
                                            },
                                            children: [
                                                {
                                                    type: "text",
                                                    text: url,
                                                    attrs: {
                                                        class: "div_class",
                                                        style: "color: #4e78fe; text-decoration: underline;",
                                                    },
                                                },
                                            ],
                                        }
                                    );
                                    lastIndex = index + url.length;
                                });
                                // 添加剩余的普通文本节点
                                if (lastIndex < text.length) {
                                    richTextNodes.push({
                                        type: "text",
                                        text: text.substring(lastIndex),
                                        style: "color: black;",
                                    });
                                }
                                item.richTextNodes = richTextNodes;
                            }
                        }
                    });
                    this.setData({
                        messages: newVal,
                    });
                }
            },
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        _tBase: tran._t("base"),
        innerAudioContext: {} as any, // 内部音频上下文
        videoUrl:
            "http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400",
        videoContext: {},
        messages: [],
        isLogOff: false, // true就是注销或拉黑  false就是可以发送消息的正常账号
        msgFail: false,
        userId: "",
        isInput: false,
        controls: false, // 是否显示默认播放控件
        autoplay: false, // 是否自动播放
        loop: false, // 是否循环播放
        muted: true, // 是否静音
        initialTime: 0, // 初始播放时间
        direction: 0, // 播放方向，0 正常，90 逆时针90度，-90 顺时针90度
        showProgressBar: false, // 是否显示进度条
        showFullscreenBtn: false, // 是否显示全屏按钮
        showPlayBtn: false, // 是否显示播放按钮
        showCenterPlayBtn: false, // 是否显示中心播放按钮
        enableProgressGesture: false, // 是否开启手势控制进度
        objectFit: "cover", // 填充模式
        poster: "", // 封面图 URL
        friendStatus: {
            friend: true,
            blockedByTarget: false,
            logout: false,
        },
        timer: null as any,
    },
    /**
     * 组件的方法列表
     */
    methods: {
        getLength(e) {
            this.triggerEvent("getLength", e);
        },
        handleRichTextTap(e: any) {
            // 取消跳转需求
            const info = e.currentTarget.dataset.info;
            // if (info) {
            //     let urlList = info.richTextNodes.filter(
            //         (item: any) => item.url
            //     );
            //     let url = urlList.length > 0 ? urlList[0].url : "";
            //     if (url) {
            //         // 打开外部链接
            //         wx.navigateTo({
            //             url: `/pages/profile/webView/webView?url=${encodeURIComponent(
            //                 url
            //             )}`,
            //         });
            //     }
            // }
        },
        linkTap(e: any) {
            const { info } = e.currentTarget.dataset;
            wx.navigateTo({
                url: `/pages/profile/webView/webView?url=${info.msg}`,
            });
        },
        previewImage(e: baseEvent) {
            const src = e.target.dataset.src;
            wx.previewMedia({
                current: 0,
                sources: [{ url: src, type: "image" }], // 需要预览的图片/视频列表 poster 视频封面
            });
        },
        playVideo(e: any) {
            const { info } = e.currentTarget.dataset;
            wx.navigateTo({
                url: `/pages/profile/componentsProfile/videoPlay/index?info=${JSON.stringify(
                    info
                )}`,
            });
        },
        handleAudio(playFlag: any, info: any) {
            console.log("====================================");
            console.log(playFlag, info);
            console.log("====================================");
            const { innerAudioContext, messages } = this.data;
            console.log(innerAudioContext);
            const that = this;
            if (playFlag) {
                innerAudioContext.play();
                innerAudioContext.onPlay(() => {
                    // 音频开始播放执行
                    console.log("开始播放");
                });
                innerAudioContext.onEnded((res: any) => {
                    // 音频播放完后执行
                    // 全部都变成不是正在播放的状态
                    messages.map((item: any) => {
                        item.currentRead = false;
                    });
                    that.setData({
                        messages,
                    });
                    // innerAudioContext.destroy();
                    if (info.ext[this.data.userId]) return;
                    this.triggerEvent("sendCMDMessage", info);
                });
                if (
                    !innerAudioContext.buffered ||
                    info.customExts.length == "1"
                ) {
                    // 错误的音频
                    if (this.data.timer) {
                        clearTimeout(this.data.timer);
                    }
                    const timer = setTimeout(() => {
                        messages.map((item: any) => {
                            item.currentRead = false;
                        });
                        that.setData({
                            messages,
                        });
                    }, 1000);
                    this.setData({ timer: timer });
                    console.log("stop");
                    if (info.ext[this.data.userId]) return;
                    this.triggerEvent("sendCMDMessage", info);
                }
            } else {
                // innerAudioContext.pause()
                innerAudioContext.stop();
                if (info.ext[this.data.userId]) return;
                this.triggerEvent("sendCMDMessage", info);
            }
            innerAudioContext.onError((res: any) => {
                console.log(res.errMsg);
                innerAudioContext.stop();
            });
            this.setData({
                innerAudioContext,
            });
        },
        // 播放录音
        async playVoice(e: any) {
            const { info } = e.currentTarget.dataset;
            const { messages, innerAudioContext } = this.data;
            innerAudioContext.stop();
            const filePath = info.customExts.url;
            let playFlag = true;
            innerAudioContext.src = filePath;
            messages.length > 0 &&
                messages.map((item: any) => {
                    if (item.id == info.id) {
                        item.currentRead = !item.currentRead;
                        playFlag = item.currentRead == true ? true : false;
                    } else {
                        item.currentRead = false;
                    }
                });
            this.setData(
                {
                    innerAudioContext,
                    messages,
                },
                () => {
                    this.handleAudio(playFlag, info);
                }
            );
        },
    },
});
